// db.js
import { openDB } from 'idb';
import ZYBW from '@/util/request/index.js';
import { getBeiAnType, BeiAnTypeEnum } from '@/bean/BeiAnType';
// 打开数据库
const initDB = openDB('zyt-database', 1, {
    upgrade(db) {
        const store = db.createObjectStore('FilingMain', {
            keyPath: 'id',
            autoIncrement: true,
        });
        store.createIndex('userid', 'userid', { unique: false });
        store.createIndex('filingNumber', 'filingNumber', { unique: false });
    },
});

// 添加或更新数据
async function addOrUpdateData(otherData) {
    const db = await initDB;

    const tx = db.transaction('FilingMain', 'readwrite');
    const store = tx.store;
    const index = store.index('filingNumber');

    let allUserData = await index.getAll(otherData.filingNumber);

    let maxSeqnoRecord = null;
    for (const item of allUserData) {
        if (!maxSeqnoRecord || item.seqNo > maxSeqnoRecord.seqNo) {
            maxSeqnoRecord = item;
        }
        await store.delete(item.id);
    }
    const currentTime = new Date().toISOString();
    const userId = localStorage.getItem('uid');
    let varietyNames = '';
    let filingSaleDTOList;
    if (otherData.varietyInfos != null && otherData.varietyInfos) {
        filingSaleDTOList = JSON.parse(otherData.varietyInfos);
        filingSaleDTOList.forEach(item => {
            varietyNames += item.varietyName;
        });
    }
    // debugger
    if (!maxSeqnoRecord) {
        await store.put({
            userid: userId,
            varietyNames: varietyNames,
            filingSaleDTOList: filingSaleDTOList,
            timestamp: currentTime,
            ...otherData,
        });
        console.log('Data added/updated successfully1');
    } else if (maxSeqnoRecord.seqNo == null || maxSeqnoRecord.seqNo == 'undefined' || otherData.seqNo >= maxSeqnoRecord.seqNo) {
        await store.put({
            id: maxSeqnoRecord.id,
            userid: userId,
            varietyNames: varietyNames,
            filingSaleDTOList: filingSaleDTOList,
            timestamp: currentTime,
            ...otherData,
        });
        console.log('Data added/updated successfully2');
    } else {
        console.log('No update needed, existing seqno is greater');
    }

    await tx.done;
}

// 根据userid查询所有数据
async function getDataByUserId() {
    const userId = localStorage.getItem('uid');
    const db = await initDB;
    const tx = db.transaction('FilingMain', 'readonly');
    const store = tx.store;
    const index = store.index('userid');

    const allUserData = await index.getAll(userId);
    await tx.done;

    return allUserData;
}

// 根据流水号查询seqNo最大的数据
async function getDataByFilingNumber(filingNumber) {

    const db = await initDB;

    const tx = db.transaction('FilingMain', 'readwrite');
    const store = tx.store;
    const index = store.index('filingNumber');

    const allUserData = await index.getAll(filingNumber);
    await tx.done;
    let maxSeqnoRecord = null;
    allUserData.forEach(item => {

        if (!maxSeqnoRecord || item.seqNo > maxSeqnoRecord.seqNo) {
            maxSeqnoRecord = item;
        }
    });
    if (maxSeqnoRecord.fileUrl) {
        maxSeqnoRecord.filesUrl = JSON.parse(maxSeqnoRecord.fileUrl);
    }
    console.log('流水号查询：', filingNumber, maxSeqnoRecord);
    return maxSeqnoRecord;
}

// 添加或更新数据
async function addOrUpdateDatas(otherData) {
    for (const data of otherData) {
        await addOrUpdateData(data);
    }
}

// 获取待备案列表
async function getDaiBeiAn(type) {

    const userId = localStorage.getItem('uid');
    const db = await initDB;
    const tx = db.transaction('FilingMain', 'readonly');
    const store = tx.store;
    const index = store.index('userid');

    const allUserData = await index.getAll(userId);
    await tx.done;

    const data = allUserData.filter(item => item.filingStatus.toString() == '-1' && item.filingType.toString() == type).sort((a, b) => new Date(b.createDate) - new Date(a.createDate));
    // console.log(type);
    // console.log(allUserData);
    // console.log(data);
    return data;
}

// 获取seqno的最大值
async function getMaxSeqno(userId) {
    const db = await initDB;
    const tx = db.transaction('FilingMain', 'readonly');
    const store = tx.store;
    const index = store.index('userid');

    const allUserData = await index.getAll(userId);
    await tx.done;
    let maxSeqnoRecord = null;
    allUserData.forEach(item => {

        if (!maxSeqnoRecord || item.seqNo > maxSeqnoRecord.seqNo) {
            maxSeqnoRecord = item;
        }
    });

    return maxSeqnoRecord == null ? 0 : maxSeqnoRecord.seqNo;
}

// 初始化数据并保存
async function initDataHttpUser(userid) {
    try {
        let count = await getDataByUserId()
        if (count.length > 0) {

            ZYBW.get({
                url: '/api/seedarchive/initList',
                params: {
                    size: 150,
                    endDate: '2024-07-31',
                    userId: localStorage.getItem('uid'),
                },
            })
                .then((res) => {
                    console.log(res);
                    if (res&&res.code&&res.code == 200) {

                        addOrUpdateDatas(res.data);
                    }

                })
                .catch((err) => {
                    console.log(err);
                });
        }
    } catch (error) {
        console.error('Failed to fetch data:', error);
    }
}

// 刷新数据
async function pushHotDbToApp(userid) {
    try {
        const userId = localStorage.getItem('uid');
        const seqNo = await getMaxSeqno(userId);
        const { code, msg, data } = await ZYBW.get({
            url: '/api/seedarchive/pushHotDbToApp',
            params: {
                seqNo: seqNo,
                userid: userId,
            },
        });

        // console.log("wwwwwwwwwww", data);
        if (code && code == 200) {
            await addOrUpdateDatas(data);
        }
    } catch (error) {
        console.error('Failed to fetch data:', error);
    }
}


// 根据userid查询所有数据 Idb
async function zhuanfaList() {

    const db = await initDB;
    const tx = db.transaction('FilingMain', 'readonly');
    const store = tx.store;
    const index = store.index('userid');
    const uid = localStorage.getItem('uid')

    const allUserData = await index.getAll(uid);
    // debugger
    await tx.done;
    // debugger
    var arr = []
    allUserData.forEach(item => {
        if (item.filingStatus == 2 && (item.filingType == 2 || item.filingType == 4) && item.isManualOperation == 1) {
            var arrItem = []
            item.filingSaleDTOList.forEach(item2 => {
                //没转发是null
                if (null == item2.remainCount) {
                    // debugger
                    item2.remainCount = item2.confirmPackageCount;
                }
                if (null != item2.remainCount && item2.remainCount > 0) {
                    arrItem.push(item)
                }

            })
            if (arrItem.length > 0) {
                arr.push(item)
            }
        }
    })
    return arr;
}


// 获取备案列表
async function getBeiAnList(type) {

    const userId = localStorage.getItem('uid');
    const db = await initDB;
    const tx = db.transaction('FilingMain', 'readonly');
    const store = tx.store;
    const index = store.index('userid');

    const allUserData = await index.getAll(userId);
    await tx.done;

    // console.log('allUserData',allUserData);
    
    var arr = []
    let temp;
    allUserData.sort((a, b) => new Date(b.applyDate) - new Date(a.applyDate)).forEach(item => {
        // console.log('item',allUserData,arr,item,);
        if (type.indexOf(item.filingStatus.toString()) !== -1) {

            if (temp && isDifferenceGreaterThanFiveSeconds(item.applyDate, temp)) {
                item.isShowTime = false;
            } else {
                item.isShowTime = true;
                temp = item.applyDate
            }
            item.typeEnum = getBeiAnType(item.filingType)
            arr.push(item)
        }
    })
    // console.log('allUserData',allUserData,arr,);
    return arr;
}
function isDifferenceGreaterThanFiveSeconds(time1, time2) {
    // 将时间字符串转换为 Date 对象
    const date1 = new Date(time1);
    const date2 = new Date(time2);

    // 计算两个时间的差值，单位是毫秒
    const differenceInMilliseconds = Math.abs(date1 - date2);

    // 转换 5 分钟为毫秒
    const fiveSecondsInMilliseconds = 5 * 60 * 1000;

    // 判断差值是否小于于 5 分钟
    return differenceInMilliseconds < fiveSecondsInMilliseconds;
}
export {
    addOrUpdateData,
    getDataByUserId,
    initDataHttpUser,
    getDaiBeiAn,
    pushHotDbToApp,
    getDataByFilingNumber,
    zhuanfaList,
    getBeiAnList,
};
